Skip to content

B040: count logger.exception() and similar calls as using the exception - #632

Open
nafiurahman00 wants to merge 1 commit into
PyCQA:mainfrom
nafiurahman00:b040-implicit-exception-use
Open

nafiurahman00 wants to merge 1 commit into
PyCQA:mainfrom
nafiurahman00:b040-implicit-exception-use

Conversation

@nafiurahman00

Copy link
Copy Markdown

B040 reports a false positive when a note is added to the caught exception and the exception is then logged without being passed in explicitly:

try:
    ...
except Exception as e:
    e.add_note("while loading config")
    logger.exception("failed")  # B040 Exception with added note not used

logger.exception() logs the exception currently being handled, and the note shows up in the output, so nothing was dropped. Same for logger.error(..., exc_info=True), traceback.print_exc(), traceback.format_exc() and sys.exc_info(). Passing e to any call (even print(e)) already counts as using it, these calls just don't take it as an argument.

This change treats those calls as a use as well:

  • any .exception(...) call (logging.exception, logger.exception, sys.exception)
  • traceback.print_exc() / traceback.format_exc() / sys.exc_info(), including when imported directly (from traceback import print_exc)
  • any call with exc_info=True

exc_info=False is still reported. I found this by running bugbear on the CPython stdlib, which flags _pyrepl/console.py. That one calls its own showsyntaxerror(), which reads the exception from sys.exc_info() internally, so it's still reported with this change. I didn't try to cover helper functions like that.

Added cases to tests/eval_files/b040.py. They fail without the change, and the test suite and pre-commit pass.

B040 fired when a note was added to the caught exception and the
exception was then logged with logger.exception(), exc_info=True or
traceback.print_exc(). Those all report the exception being handled,
note included, so nothing is lost. Passing the exception in (e.g.
print(e)) already counted as using it, these calls just don't take it
as an argument.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant